package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.result.R;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;


@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService{
    @Autowired
    private EmployeeService employeeService;


    @Override
    public R<Employee> login(HttpServletRequest request,Employee employee) {
        //1.将页面提交的密码进行加密
        String password = employee.getPassword();
       password = DigestUtils.md5DigestAsHex(password.getBytes());

       //2.根据页面提交的用户名查询数据库
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
         lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        //3.如果没有查询到返回登录失败
        if (null == emp) {
            return R.error("用户名不存在");
        }

        //4.密码比对，不一致返回失败
        if (!emp.getPassword() .equals(password) ) {
            return R.error("密码错误");
        }

        //5.查看员工状态 是否禁用
        if (emp.getStatus() == 0) {
            return R.error("账户已被禁用");
        }

        //6.登陆成功，存入session
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }
}
